<script setup>
import { getFavoritesList, getFavoritesDetail, getMusicList, deleteMusic, getMusicDetail, editMusic, getMusicMoreList } from "@/utils/api/music";
import { dayjs, ElMessage } from "element-plus";
import { ref, onMounted } from "vue";
import { useUserStore } from "@/store/modules/useUserStore";

const BASE_URL = import.meta.env.VITE_BASE_URL;
const STATIC_URL = import.meta.env.VITE_STATIC_URL;

const userId = useUserStore().userInfo.id;

const favoriteData = ref([]);
const musicata = ref([]);
const loading = ref(false);

const f_pageSize = ref(10);
const f_currentPage = ref(0);
const f_total = ref(0);
const fetchData = async () => {
  loading.value = true;
  const favorites = await getFavoritesList({
    pageNum: f_pageSize.value,
    pageSize: f_currentPage.value
  });
  if (favorites.success) {
    favoriteData.value = favorites.data.list;
    f_total.value = favorites.data.count;
  }

  loading.value = false;
};

const pageSize = ref(20);
const currentPage = ref(0);
const total = ref(0);
const musiclaoding = ref(false);
const keyword = ref("");
const is_musicMore = ref(null);

const dataInit = async () => {
  musiclaoding.value = true;
  const musics = await getMusicList({
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    title: keyword.value,
    artist: keyword.value,
    album: keyword.value,
    isMusicMore: is_musicMore.value
  });
  if (musics.success) {
    musicata.value = musics.data.list;
    total.value = musics.data.count;
  }
  musiclaoding.value = false;
};

const handleDelete = async (ids) => {
  const res = await deleteMusic({ ids });
  if (res.success) {
    ElMessage.success("删除成功");
    dataInit();
  } else {
    ElMessage.error("删除失败");
  }
};

onMounted(async () => {
  fetchData();
  dataInit();
  // 获取音频元素
  const audioElement = document.getElementById("myAudio");
  // 添加 'ended' 事件监听器
  audioElement.addEventListener("ended", function () {
    if (musicata.value.length > playingIndex.value + 1) {
      playingIndex.value++;
      playingMusic.value = musicata.value[playingIndex.value];
    } else {
      playingIndex.value = 0;
      playingMusic.value = musicata.value[playingIndex.value];
    }
  });
});

/* 播放音乐 */
const playingMusic = ref({});
const playingIndex = ref(0);
const handlePlay = (row) => {
  playingMusic.value = row;
  playingIndex.value = musicata.value.findIndex((item) => item.id === row.id);
};

const getFavoritesMusic = async (row) => {
  const musicRes = await getFavoritesDetail({ id: row.id });
  if (musicRes.success) {
    musicata.value = musicRes.data.music;
    total.value = 0;
  }
};

// 获取详情
const muiscInfo = ref({});
const getMuiscInfo = async (row) => {
  try {
    const musicRes = await getMusicDetail({ id: row.id });
    if (musicRes.success) {
      muiscInfo.value = musicRes.data;
      musicName.value = musicRes.data.title;
    }
  } catch (error) {
    console.log(error);
  }
};

// 获取网络歌曲
const musicName = ref("");
const musicMoreList = ref([]);
const getNetMusicMoreList = async () => {
  try {
    const musicRes = await getMusicMoreList({
      word: musicName.value
    });
    if (musicRes.success) {
      musicMoreList.value = musicRes.data.list;
    }
    ElMessage({
      message: musicRes.message,
      type: musicRes.success ? "success" : "error"
    });
  } catch (error) {
    console.log(error);
  }
};

// 编辑音乐
const musicLoading = ref(false);
const editMusicInfo = async (m_id) => {
  musicLoading.value = true;
  try {
    const musicRes = await editMusic({
      id: muiscInfo.value.id,
      m_id: String(m_id),
      uid: userId
    });
    ElMessage({
      message: musicRes.message,
      type: musicRes.success ? "success" : "error"
    });
  } catch (error) {
    console.log(error);
  }
  musicLoading.value = false;
};

/* 详情 */
const editVisible = ref(false);
const handleDetail = (row) => {
  editVisible.value = true;
  getMuiscInfo(row);
};

const onCloseEdit = () => {
  editVisible.value = false;
  musicName.value = "";
  musicMoreList.value = [];
  muiscInfo.value = {};
};
</script>
<template>
  <div>
    <el-card class="box-card" shadow="never">
      <div class="felx-nowrap">
        <div class="favorite-container">
          <h3 class="m-l">收藏夹</h3>
          <el-table
            :data="favoriteData"
            id="favorite-table"
            v-loading="loading"
            element-loading-text="Loading..."
            @current-change="getFavoritesMusic"
          >
            <el-table-column label="封面" width="80">
              <template #default="scope">
                <el-image class="image" :src="BASE_URL + 'Thumbnail/' + scope.row.favorites_cover" fit="cover" />
              </template>
            </el-table-column>
            <el-table-column prop="favorites_name" label="收藏夹名称" />
            <el-table-column prop="musicCount" label="歌曲数量" />
            <el-table-column label="创建时间">
              <template #default="scope">
                {{ dayjs(scope.row.create_time).format("YYYY-MM-DD") }}
              </template>
            </el-table-column>
          </el-table>
          <div class="f_pagination">
            <el-pagination
              v-model:current-page="f_currentPage"
              v-model:page-size="f_pageSize"
              :page-sizes="[20, 100, 200, 300, 400]"
              layout="total, sizes, prev, pager, next"
              :total="f_total"
              background
              @size-change="fetchData"
              @current-change="fetchData"
            />
          </div>
          <div class="audio">
            <el-popover
              class="box-item"
              width="300"
              :title="playingMusic.title || '暂无播放的歌曲'"
              :content="playingMusic.artist ? playingMusic.artist + ' - ' + playingMusic.album : ''"
              placement="top"
            >
              <template #reference>
                <audio id="myAudio" controls :src="STATIC_URL + playingMusic.file_name" autoplay />
              </template>
            </el-popover>
          </div>
        </div>
        <div class="flex-grow-1"></div>
        <div class="table-container">
          <el-form :inline="true" class="felx-nowrap">
            <el-form-item>
              <el-input placeholder="请输入音乐关键字进行搜索" v-model="keyword" clearable />
            </el-form-item>
            <el-form-item>
              <el-select v-model="is_musicMore" placeholder="是否有扩展信息" clearable>
                <el-option label="有扩展信息" value="1" />
                <el-option label="无扩展信息" value="0" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button icon="Search" type="primary" @click="dataInit">搜索 </el-button>
            </el-form-item>
          </el-form>
          <el-table :data="musicata" id="music-table" v-loading="musiclaoding" element-loading-text="Loading...">
            <el-table-column prop="title" label="歌曲名称" show-overflow-tooltip />
            <el-table-column label="艺术家" show-overflow-tooltip>
              <template #default="scope">
                {{
                  (scope.row.artists && scope.row.artists?.length > 0 ? scope.row.artists.join("/") : "未知歌手") +
                  " - " +
                  (scope.row.album ?? "未知专辑")
                }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="160">
              <template #default="scope">
                <el-button type="success" icon="VideoPlay" circle @click="handlePlay(scope.row)" />
                <el-button type="primary" icon="More" circle @click="handleDetail(scope.row)" />
                <el-popconfirm title="确认删除?" @confirm="handleDelete([scope.row.id])">
                  <template #reference>
                    <el-button type="danger" icon="Delete" circle />
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
          <div class="m-t">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[20, 100, 200, 300, 400]"
              layout="total, sizes, prev, pager, next"
              :total="total"
              background
              @size-change="dataInit"
              @current-change="dataInit"
            />
          </div>
        </div>
      </div>
    </el-card>
    <el-dialog v-model="editVisible" @closed="onCloseEdit" title="音乐详情" width="80%">
      <el-descriptions class="margin-top" title="基本信息" :column="3" :size="size" border>
        <template #extra>
          <el-input v-model="musicName" style="width: 240px" placeholder="请输入歌曲名称进行搜索" class="m-r" />
          <el-button type="primary" @click="getNetMusicMoreList">搜索网络歌曲</el-button>
        </template>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">歌曲名称</div>
          </template>
          {{ muiscInfo.title }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">歌手</div>
          </template>
          {{ muiscInfo.artist }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">艺术家</div>
          </template>
          {{ muiscInfo.artists?.join("/") }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">专辑</div>
          </template>
          <el-tag size="small">{{ muiscInfo.album }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">文件名称</div>
          </template>
          {{ muiscInfo.file_name }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">扩展信息</div>
          </template>
          <el-tag type="primary" v-if="muiscInfo.musicMore">有扩展信息</el-tag>
          <el-tag type="info" v-else>无扩展信息</el-tag>
        </el-descriptions-item>
      </el-descriptions>
      <el-table
        v-if="musicMoreList.length > 0"
        v-loading="musicLoading"
        element-loading-text="修改中..."
        :data="musicMoreList"
        style="width: 100%"
        class="m-t"
      >
        <el-table-column prop="id" label="ID" />
        <el-table-column prop="title" label="歌曲名称" />
        <el-table-column prop="artist" label="歌手" show-overflow-tooltip />
        <el-table-column prop="album" label="专辑" />
        <el-table-column label="封面">
          <template #default="scope">
            <el-image class="image-item" :src="scope.row.cover" fit="cover" />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-popconfirm title="确认匹配这首歌曲?" @confirm="editMusicInfo(scope.row.id)">
              <template #reference>
                <el-button type="warning" icon="Edit" circle />
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.f_pagination {
  overflow-x: auto;
  margin-top: 16px;
}
.flex-grow-1 {
  width: 20px;
}
.favorite-container {
  width: 38%;
}
.table-container {
  width: 58%;
}
#favorite-table {
  width: 100%;
  height: calc(100vh - 270px);
}
#music-table {
  width: 100%;
  height: calc(100vh - 222px);
}
.audio {
  width: 100%;
  margin-top: 12px;
  display: flex;
  justify-content: center;
}
.image {
  width: 40px;
  height: 40px;
  border-radius: 6px;
}
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
.title {
  font-size: 14px;
  font-weight: bold;
}
.artist {
  font-size: 12px;
}
.image-item {
  width: 50px;
  height: 50px;
  border-radius: 4px;
}
</style>
